package com.hh.releasenode.controller;

import com.hh.releasenode.controller.AbstractController;
import com.hh.releasenode.form.LoginForm;
import com.hh.releasenode.service.SysCaptchaService;
import com.hh.releasenode.service.SysUserService;
import com.hh.releasenode.utils.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author KunxianLi
 * Date 2020/5/29 17:08
 * Version 1.0
 **/
@RestController
@Api(tags = "登陆相关接口")
@RequestMapping("/admin")
public class LoginController extends AbstractController {

    @Autowired
    private SysCaptchaService sysCaptchaService;

    @Autowired
    private SysUserService sysUserService;


    @ApiOperation("获取验证码")
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response,@RequestParam(name="uuid") String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);

    }

    /**
     * @Author KunxianLi
     * @Description 可使用用户名或手机号登陆
     * @Date 2020/7/4 14:28
     * @Param [form]
     * @return com.hh.releasenode.utils.Response
     **/
    @ApiOperation("系统用户登陆")
    @PostMapping("/login")
    public Response login(@RequestBody LoginForm form){

        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());

        if(!captcha){
            return Response.error("验证码不正确");
        }

        sysUserService.login(form.getUsername(),form.getPassword());

        return Response.success();

    }

    @ApiOperation("系统用户登出")
    @PostMapping("/logout")
    public Response logout(HttpServletRequest request){
        String token = getToken(request);
        sysUserService.logout(token);
        return Response.success();

    }



}
